package com.bfly.mall.product.service.impl;

import com.bfly.core.base.service.BaseServiceImpl;
import com.bfly.mall.product.dao.ProductFavoriteMapper;
import com.bfly.mall.product.entity.ProductFavorite;
import com.bfly.mall.product.service.IProductFavoriteService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;

/**
 * @author 长沙商脉科技有限公司
 * @date 2020/9/21 12:32
 */
@Service
public class ProductFavoriteServiceImpl extends BaseServiceImpl<ProductFavorite, Integer> implements IProductFavoriteService {

    @Autowired
    private ProductFavoriteMapper favoriteMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(int userId, int productId) {
        ProductFavorite favorite = favoriteMapper.getFavorite(userId, productId);
        if (favorite == null) {
            favorite = new ProductFavorite();
            favorite.setProductId(productId);
            favorite.setUserId(userId);
            favorite.setCreateDate(new Date());
            super.save(favorite);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void unFavorite(int userId, int productId) {
        ProductFavorite favorite = favoriteMapper.getFavorite(userId, productId);
        if (favorite != null) {
            super.remove(favorite.getId());
        }
    }

    @Override
    public boolean isFavorite(int userId, int productId) {
        ProductFavorite favorite = favoriteMapper.getFavorite(userId, productId);
        return favorite != null;
    }
}